using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using System.IdentityModel.Tokens.Jwt;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Middleware
{
    /// <summary>
    /// JWT中间件 - 处理JWT令牌的提取和验证
    /// </summary>
    public class JwtMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<JwtMiddleware> _logger;

        public JwtMiddleware(RequestDelegate next, ILogger<JwtMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context, IJwtService jwtService)
        {
            var token = ExtractTokenFromRequest(context.Request);
            
            if (!string.IsNullOrEmpty(token))
            {
                var (isValid, principal) = jwtService.ValidateAccessToken(token);
                
                if (isValid && principal != null)
                {
                    context.User = principal;
                    
                    // 记录用户信息到日志中
                    var userId = principal.FindFirst("sub")?.Value ?? principal.FindFirst("nameid")?.Value;
                    var userName = principal.FindFirst("unique_name")?.Value ?? principal.FindFirst("name")?.Value;
                    
                    _logger.LogDebug("JWT验证成功 - UserId: {UserId}, UserName: {UserName}", userId, userName);
                }
                else
                {
                    _logger.LogWarning("JWT验证失败 - Token: {Token}", token);
                }
            }

            await _next(context);
        }

        private static string? ExtractTokenFromRequest(HttpRequest request)
        {
            var authorizationHeader = request.Headers.Authorization.FirstOrDefault();
            
            if (!string.IsNullOrEmpty(authorizationHeader) && authorizationHeader.StartsWith("Bearer "))
            {
                return authorizationHeader["Bearer ".Length..];
            }

            // 也可以从查询参数中获取token
            if (request.Query.ContainsKey("access_token"))
            {
                return request.Query["access_token"];
            }

            return null;
        }
    }

    /// <summary>
    /// JWT中间件扩展方法
    /// </summary>
    public static class JwtMiddlewareExtensions
    {
        /// <summary>
        /// 添加JWT中间件
        /// </summary>
        /// <param name="builder">应用程序构建器</param>
        /// <returns>应用程序构建器</returns>
        public static IApplicationBuilder UseJwtMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<JwtMiddleware>();
        }
    }
}
